﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QD.UpDownLoad
{
    public static class WebClientHelper
    {

        /// <summary>
        /// 服务器ip及端口
        /// </summary>
        public static string ServerUri = ConfigurationManager.AppSettings["SyncAPIBaseUrl"];

        public class ClientResultDTO
        {
            public bool success { get; set; }
            public object data { get; set; }
            public string error { get; set; }
        }

        public static ClientResultDTO DownloadString(string uri)
        {
            string url = "";
            if (string.IsNullOrEmpty(uri))
            {
                url = ServerUri;
            }
            else
            {
                url = uri;
            }

            //构造真实url（康剑民 2021-06-17）
            if (uri.ToLower().StartsWith("http://") || uri.ToLower().StartsWith("https://"))
            {
                url = uri;
            }
            else
            {
                if (url.EndsWith("/") && uri.StartsWith("/"))
                {
                    url = url + uri.Substring(1, uri.Length - 1);
                }
                else if ((url.EndsWith("/") && !uri.StartsWith("/")) || (!url.EndsWith("/") && uri.StartsWith("/")))
                {
                    url = url + uri;
                }
                else
                {
                    url = url + "/" + uri;
                }
            }

            System.Net.WebClient myWebClient = new System.Net.WebClient();
            myWebClient.Encoding = System.Text.Encoding.UTF8;

            string mod = myWebClient.DownloadString(url);

            ClientResultDTO user = JsonConvert.DeserializeObject<ClientResultDTO>(mod);

            return user;
        }
    }
}
